import React from 'react';
import './index.scss'
import Square from "../Square";
interface IBoard {
    name: string;
    xIsNext: boolean;
    winner: string | null;
    squares: string[] | null[];
}

class Board extends React.Component <any, IBoard>{
    constructor(props: IBoard) {
        super(props);
        this.state = {
            name: 'mark',
            xIsNext: true,
            winner: null,
            squares: Array(9).fill(null)
        }
    }
    handleClick(i:number) {
        const squares = this.state.squares.slice();
        squares[i] = this.nexPlayer();
        this.setState({
            squares: squares,
            xIsNext: !this.state.xIsNext
        })
        const winner = this.calcWinner(squares)
        if(winner){
            this.setState({
                winner: winner
            })
        }
    }

    reStart() {
        this.setState({
            name: 'mark',
            xIsNext: true,
            winner: null,
            squares: Array(9).fill(null)
        })
    }

    renderGameOver() {
        const winner = this.state.winner
        if(winner) {
            return (
                <div className="game-result">
                    The winner is {winner}
                    <button className='re-start' onClick={() => this.reStart()}>再来一局</button>
                </div>
            )
        } else {
            return null
        }
    }

    renderSquare(i: number) {
        return <Square
            value={this.state.squares[i]}
            key={i}
            onClick={() => this.handleClick(i)}
        />;
    }

    renderSquareList() {
        let res = []
        for(let i=0; i<9; i++) {
            res.push( this.renderSquare(i))
        }
        return res
    }

    nexPlayer() {
        return this.state.xIsNext ? 'X' : 'O'
    }

    calcWinner(squares: (string | null)[]) {
        const winConditions = [
            [0, 1, 2],
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6],
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8],
            [2, 4, 6],
        ]

        for(let i = 0; i < winConditions.length; i++) {
            const [a,b,c] = winConditions[i]
            if (
                squares[a]
                && squares[a] === squares[b]
                && squares[a] === squares[c]
            ) {
                return squares[a]
            }
        }
    }

    render() {
        const status = 'Next player: ' + this.nexPlayer();

        return (
            <div className="game-box">
                <div className="status">{status}</div>
                <div className="item-list">
                {
                    this.renderSquareList()
                }
                </div>
                {
                    this.renderGameOver()
                }
            </div>
        );
    }
}

export default Board
